import {appconstant} from '../common/constant'
import {
  LOGIN
} from '../actions'
import { Toast } from 'antd-mobile'

let token = ""
if( sessionStorage.getItem("TcslSlyunToken") ){
	token = sessionStorage.getItem("TcslSlyunToken")
}
export default store => next => action => {
	const postd = action['post']
	const getd = action['get']
	const putd = action['put']
	console.log(putd)
	const getdata = ( url ) => {
		return fetch( appconstant.servers[appconstant.servers.profile].host+url,{
			headers: {
			    'Tcsl-Slyun-Token': token
			}
		}).then( res=>res.json().then(
							json => {
								if( !res.ok ){
									return Promise.reject(json)
								}
		
								return json
							}
					  )
					  
				)
	}

	const postdata = ( url,data ) => {
		let headersobj = {
			'Accept': 'application/json',
	      	'Content-Type': 'application/json'
		}
		if( postd && postd.type !== LOGIN ){
			headersobj['Tcsl-Slyun-Token'] = token
		}

		return fetch( appconstant.servers[appconstant.servers.profile].host+url, {  
		    method: 'post',
		    body: JSON.stringify( data ),
		 	mode:'cors',
		    headers: headersobj
		}).then( res=>res.json().then(
			json=>{
				if( postd && postd.type === LOGIN ){
					// console.log( "asdd",res.headers.get("Tcsl-Slyun-Token") )
					token = res.headers.get("Tcsl-Slyun-Token")
					sessionStorage.setItem("TcslSlyunToken", token)
				}
				
				if( !res.ok ){
					return Promise.reject(json)
				}

				return json
			}
		) )
	}

	const putdata = ( url,data ) => {
		return fetch( appconstant.servers[appconstant.servers.profile].host+url, {  
		    method: 'put',
		    body: JSON.stringify( data ),
		 	mode:'cors',
		    headers: {
				'Accept': 'application/json',
		      	'Content-Type': 'application/json',
		      	'Tcsl-Slyun-Token':token
			}
		}).then( res=>res.json().then(
			json=>{
				if( !res.ok ){
					return Promise.reject(json)
				}

				return json
			}
		) );
	}
	Toast.loading('Loading...', 0)
	if( postd ){
		return postdata( action.url,action.data ).then(
			res => {
				next( { data:res,type:postd.type,params:action.data } )
			},
			err => {
				//后期要做成派发一个错误的事件
				alert( "网络出问题了" )
				// next( { data:err,type:postd.type } )
			}
		)
	}else if( getd ){

		let urlarr = action.url.split( "/" )

		return getdata( action.url ).then(
				res => next( { data:res,type:getd.type,params:urlarr[ urlarr.length-1 ] } ),
				err => {
					alert( "网络出问题了" )
					// next( { data:err,type:getd.type } )
				}
		)
	}else if( putd ){

		let urlarr = action.url.split( "/" )
		action.data.urlparam = urlarr[ urlarr.length-1 ]
		return putdata( action.url,action.data ).then(
				res => next( { data:res,type:putd.type,params:action.data } ),
				err => {
					alert( "网络出问题了" )
					// next( { data:err,type:putd.type } )
				}
		)
	}else{
		return next(action)
	}


}